<#import "/spring.ftl" as spring />
<#import "../layout/defaultLayout.ftl" as layout>
<@layout.defaultLayout styles=["bootstrap-table/bootstrap-table.min.css",
"bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css",
"bootstrap-validator/css/bootstrapValidator.css",
"x-editable/bootstrap3-editable/css/bootstrap-editable.css"]
scripts=["bootstrap-table/bootstrap-table.min.js",
"bootstrap-table/locale/bootstrap-table-zh-CN.min.js",
"bootstrap-validator/validator.js",
"jquery/serializejson/jquery.serializejson.min.js",
"util/jquery-dateFormat.min.js",
"bootstrap-table/extensions/export/bootstrap-table-export.min.js",
"bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js",
"bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js",
"bootstrap-table/extensions/editable/bootstrap-table-editable.js",
"x-editable/bootstrap3-editable/js/bootstrap-editable.js",
"bootstrap-validator/js/bootstrapValidator.js",
"util/tableExport.js"]>

<div class="container-fluid">
        <div class="container">
        <fieldset>
				<legend>	
					<span class="glyphicon glyphicon-th-list"></span>&nbsp;&nbsp;<@spring.message "config.reportConfigLegend" />
				</legend>
				<div class="row clearfix">
					<div class="col-md-7 column">
						<div id="toolbar">
							<button id="addGroup" class="btn btn-success" data-toggle="modal" data-target="#groupFieldModal">
					            <i class="glyphicon glyphicon-plus"></i><@spring.message "button.add"/>
					        </button>
					        <button id="editGroup" class="btn btn-success" data-toggle="modal">
					            <i class="glyphicon glyphicon-pencil"></i><@spring.message "button.edit"/>
					        </button>	
					        <button id="removeGroup" class="btn btn-success" >
					            <i class="glyphicon glyphicon-remove"></i><@spring.message "button.delete"/>
					        </button>	
					        	        
					    </div>
		         	 	<table  id="groupFieldTable" data-classes="table table-hover table-striped" 
						           data-toolbar="#toolbar" data-toggle="table"  data-page-list="[5]" 
						           data-pagination="true" data-page-size="5" data-side-pagination="client"
						           data-method="post"
						           data-url="${request.contextPath}/report/configure/colConf/queryGroup/${reportId}">
						           
						            <thead>	
							            <tr>
							             	<th data-field="" data-checkbox="true"></th>
							                <th data-field="groupName" data-halign="center"><@spring.message "field.groupField" /></th>
							                <th data-field="dataCols" data-halign="center"><@spring.message "field.fieldName" /></th>
							                 <th data-field="colJson" data-visible="false"><@spring.message "field.json"/></th>
							                 <th data-field="id" data-visible="false">ID</th>
							            </tr>
							            </thead>

				    </table>
					</div>
					<div class="col-md-5 column">
					</div>
				</div>
				           <!-- 模态框（Modal） -->
		<div class="modal fade" id="groupFieldModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			<div class="modal-dialog" style="width:500px;">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
							&times;
						</button>
						<h4 class="modal-title" id="myModalLabel">
							
						</h4>
					</div>
					<div class="modal-body">
					<form class="form-horizontal" role="form" id ="groupEditForm">
						<div class="form-group">
							 <label for="groupName" class="col-sm-3 control-label"><@spring.message "field.groupName"/></label>
							 <div class="col-sm-7">
							 	<input type="input" class="form-control" id="groupName" name="groupName" />
							 </div>
							 <label for="groupCode" class="col-sm-3 control-label"><@spring.message "field.groupCode"/></label>
							 <div class="col-sm-7">
							 	<input type="input" class="form-control" id="groupCode" name="groupCode" />
							 </div>
						</div>
						
						<table id="modelTable" data-classes="table table-hover table-striped" data-toggle="table"
							data-page-size="50">
							 <thead>	
							            <tr>
							             	<th data-field="check" data-checkbox="true"></th>
							                <th data-field="colCode" data-halign="center"><@spring.message "field.colCodes"/></th>
							            </tr>
							            </thead>
		                </table>
		                
		                </form>
					</div>	
					 <div class="modal-footer">
						<button type="submit" class="btn btn-success" data-dismiss="modal" id="groupSureBtn"><@spring.message "button.submit"/>
						</button>
						<button type="button" class="btn btn-success" data-dismiss="modal"><@spring.message "button.shutdown"/>
						</button>
					</div>
					
				</div><!-- /.modal-content -->
			</div><!-- /.modal -->
		</div> <br/>
				<div class="alert alert-warning fade in" id="nameAlert">
				    <a href="#" class="close" >
				        &times;
				    </a>
				    <strong><@spring.message "msg.warning"/></strong><@spring.message "msg.colNameNotNull"/>
				    
				</div>
				<table  id="colConfTable" data-classes="table table-hover table-striped" 
						data-pagination="true" data-page-list="[5 ,10, 20]"
							data-side-pagination="client" data-query-params="queryParams"
							data-response-handler="responseHandler" data-method="post"
							data-url="${request.contextPath}/report/configure/colConf/getCols">
						           
				    </table>    
				    <div style="text-align: right; width: 100%;">
						<button id="lastStep" class="btn btn-success" style="width: 100px;"><@spring.message "report.lastStep"/></button>
						<button id="nextStep" class="btn btn-success" style="width: 100px;"><@spring.message "report.nextStep"/></button>
					</div>	
				</fieldset>
        </div>
        <br/><br/>
	<input type="text" name="reportId" id="reportId"  value="${reportId}" style="display:none;"/>
	<input type="text" name="reportCode" id="reportCode"  value="${reportCode}" style="display:none;"/>  
</div>
<script>	
	var  mtable  = $('#groupFieldTable');
	var colTable = $('#colConfTable');
	var modelTable = $('#modelTable');
	var groupData = []
	var colData ;
	var groupIndex = 0;
	var checkedIndex = -1;
	var doType = '';// 操作类型
	var reportId = $("#reportId").val();
	var reportCode = $("#reportCode").val();

	function queryParams(params){
		return {
		"reportId":reportId
		}
	}

	function responseHandler(res){
		var backObj
		var datas = [];
		var sortOrder = 1;
		if(res.length == 1){
			backObj = res[0];
			colData = res[0];
			for (var key in backObj){
				var row = new Object();
				//alert(key)
				row.sortOrder = sortOrder ++;
				row.code = key;
				row.name = '';
				row.type = 'String';
				row.isCondition = '';
				row.isTableCol = 'true';
				row.isHidden = '';
				row.width = '100';
				row.format ='date';
				row.sql = '';
				row.style = '';
				row.queryType = '';
				row.conditionType = '1';
				row.cascadeCondition = '';
				row.linkReport = '';
				datas.push(row);
			}
		}else{
			backObj = res;
			colData = res;
			for (var key in backObj){
				var row = new Object();
				var backObj = res[key];
				row.sortOrder = sortOrder ++;
				row.code = backObj.code;
				row.name = backObj.name;
				row.type = backObj.data_type;
				row.isCondition = backObj.isCondition;
				row.isTableCol = 'true';
				row.isHidden = backObj.is_hidden;
				row.width = backObj.width;
				row.format = backObj.format;
				row.sql = backObj.dataSql;
				row.style = backObj.style;
				row.queryType = backObj.queryType;
				row.conditionType = backObj.conditionType;
				row.cascadeCondition = '';
				row.linkReport = backObj.link_report;
				datas.push(row);
			}
		}
		
		/* for (var key in res){
			var backObj = res[key];
			var row = new Object();
			//alert(key)
			row.sortOrder = backObj.SORT_ORDER;
			row.code = backObj.CODE;
			row.name = backObj.NAME;
			row.type = backObj.DATA_TYPE;
			row.isCondition = '';
			row.isTableCol = 'true';
			row.isHidden = backObj.IS_HIDDEN;
			row.width = backObj.WIDTH;
			row.format = backObj.FORMAT;
			row.sql = '';
			row.style = backObj.STYLE;
			row.queryType = '';
			row.conditionType = '1';
			row.cascadeCondition = '';
			row.linkReport = backObj.LINK_REPORT;
			datas.push(row);
		} */
		return datas;
	}
	
	function checkFormatter(value) {
        var checked = value ? 'checked' : '';
        return '<input type="checkbox" ' + checked + ' />';
    }
	
	 window.isConditionEvents = {
		        'change :checkbox': function (e, value, row, index) {
		            row.isCondition = $(e.target).prop('checked');
		            colTable.bootstrapTable('updateRow', {
		                index: index,
		                row: row        
		            });
		        }  	
		    };
	 window.isTableColEvents = {
		        'change :checkbox': function (e, value, row, index) {
		            row.isTableCol = $(e.target).prop('checked');
		            colTable.bootstrapTable('updateRow', {
		                index: index,
		                row: row        
		            });
		        }  	
		    };
	 window.isHiddenEvents = {
		        'change :checkbox': function (e, value, row, index) {
		            row.isHidden = $(e.target).prop('checked');
		            colTable.bootstrapTable('updateRow', {
		                index: index,
		                row: row        
		            });
		        }  	
		    };
	 
	 function setAlertTimeout(){
		 setTimeout("$('#nameAlert').hide();",3000);
	 }
		
	$(function(){
		
		$("#nameAlert").hide();//bootstrap alert 
		
		$('#groupEditForm').bootstrapValidator({
	　　　　　　　　message: 'This value is not valid',
	            　feedbackIcons: {
	                　　　　　　　　valid: 'glyphicon glyphicon-ok',
	                　　　　　　　　invalid: 'glyphicon glyphicon-remove',
	                　　　　　　　　validating: 'glyphicon glyphicon-refresh'
	            　　　　　　　　   },
	            fields: {
	            	groupName: {
	                    message: "<@spring.message 'msg.nameValidateFail'/>",
	                    validators: {
	                        notEmpty: {
	                            message: "<@spring.message 'msg.nameNotNull'/>"
	                        }
	                    }
	                },
	                groupCode: {
	                    message: "<@spring.message 'msg.codeValidateFail'/>",
	                    validators: {
	                        notEmpty: {
	                            message: "<@spring.message 'msg.codeNotNull'/>"
	                        }
	                    }
	                }
	            }
	        });
		//$('#groupEditForm').data('bootstrapValidator').validate();
		colTable.bootstrapTable({
	            columns: [{
	                field: 'sortOrder',
	                title: "<@spring.message 'column.sortOrder' />",
	                halign: 'center',
	                width: '30',
	                align: 'center'
	            },{
	                field: 'code',
	                title: "<@spring.message 'field.colCodes'/>",
	                halign: 'center',
	                width: '50',
	                align: 'center'
	            },{
	            	field:'name',
	            	title: "<@spring.message 'column.name'/>",
	            	halign: 'center',
	            	editable:true,
	            	width: '70',
	            	align: 'center'
	            },{
	            	field:'isTableCol',
	            	title: "<@spring.message 'column.isTableCol' />",
	            	halign: 'center',
	            	align: 'center',
	            	width: '40',
	            	events:"isTableColEvents",
	            	formatter:'checkFormatter'
	            },{
	            	field:'isHidden',
	            	title: "<@spring.message 'column.isHidden' />",
	            	halign: 'center',
	            	align: 'center',
	            	width: '40',
	            	events:"isHiddenEvents",
	            	formatter:'checkFormatter'
	            },{
	            	field:'cascadeCondition',
	            	title:"<@spring.message 'column.cascadeCondition'/>",
	            	halign: 'center',
	            	width: '80',
	            	editable:true,
	            	align: 'center'
	            },{
	            	field:'linkReport',
	            	title: "<@spring.message 'column.linkReport' />",
	            	halign: 'center',
	            	editable:true,
	            	width: '70',
	            	align: 'center'
	            },{
	            	field:'type',
	            	title: "<@spring.message 'column.type' />",
	            	halign: 'center',
	            	visible: false,
	            	align: 'center',
	            	width: '40',
	            	editable: {
	                    type: 'select',
	                    source: [
	                        {value: 'String', text: 'String'},
	                        {value: 'Int', text: 'Int'}
	                    ]}
	            },{
	            	field:'width',
	            	title: "<@spring.message 'column.width'/>",
	            	halign: 'center',
	            	editable:true,
	            	visible:false,
	            	width: '50',
	            	align: 'center'
	            },{
	            	field:'format',
	            	title:"<@spring.message 'column.format' />",
	            	halign: 'center',
	            	editable:true,
	            	align: 'center',
	            	visible:false,
	            	width: '100',
	            	editable: {
	                    type: 'select',
	                    source: [
	                        {value: 'date', text: 'yyyy-mm-dd'},
	                        {value: 'number', text: '$9999'}
	                    ] }
	            },{
	            	field:'style',
	            	title: "<@spring.message 'column.style'/>",
	            	halign: 'center',
	            	editable:true,
	            	width: '100',
	            	visible:false,
	            	align: 'center'
	            },{
	            	field:'isCondition',
	            	title:"<@spring.message 'column.isCondition' />",
	            	halign: 'center',
	            	align: 'center',
	            	width: '40',
	            	events:"isConditionEvents",
	            	formatter:'checkFormatter'
	            },{
	            	
	            	field:'conditionType',
	            	title:"<@spring.message 'column.conditionType' />",
	            	halign: 'center',
	            	align: 'center',
	            	width: '100',
	            	editable: {
	                    type: 'select',
	                    source: [
	                        {value: '1', text: "<@spring.message 'column.textInput' />"},
	                        {value: '2', text: "<@spring.message 'column.dateInput' />"},
	                        {value: '3', text: "<@spring.message 'column.selectInput' />"}
	                    ] }
	            },{
	            	field:'queryType',
	            	title: "<@spring.message 'column.queryType' />",
	            	halign: 'center',
	            	align: 'center',
	            	width: '100',
	            	editable: {
	                    type: 'select',
	                    source: [
							{value: '', text: "<@spring.message 'select.tip'/>"},
	                        {value: '1', text: "<@spring.message 'column.staticData' />"},
	                        {value: '2', text: "<@spring.message 'column.sqlQuery' />"}
	                    ] }
	            },{
	            	field:'sql',
	            	title:"<@spring.message 'column.sql' />",
	            	halign: 'center',
	            	width: '200',
	            	editable:true,
	            	align: 'center'
	            }
	            ]
	        });
		
		$('#nextStep').click(function(){
			//alert(JSON.stringify(colTable.bootstrapTable('getData')));
			var nextFlag = 0;//控制名称是否为空
			var colData = colTable.bootstrapTable('getData');
			$.each(colData, function(i,colObj){
				if (colObj.name == ''){
					$("#nameAlert").show();
					setAlertTimeout();
					nextFlag = 1;
					return false;
				}
			 })
			if (nextFlag == 1){
				return false;
			}
			$.ajax({
    	        url:'${request.contextPath}/report/configure/colConf/submit/'+reportId,
    	        type:'post',
    	        contentType: 'application/json',
    	        data:JSON.stringify(colTable.bootstrapTable('getData')),
    	        dataType:'json',
    	        success:function(data){
    	        	//alert(reportCode);
    	        	window.location.href = data.message;
    	        }
    		});

		});
		 
		 $('#addGroup').click(function(){
			 doType = 'add'
			 var modelField = []
			 //---add in 1114
			 if(colData.length > 1){
				 //var obj = colData[0];
				/*  for (var key in obj){
					 var colObj = obj[key];
					 fields = {};
					 fields.colCode = colObj.code;
					 modelField.push(fields);
				 } */
				 $.each(colData,function(i,item){
					 fields = {};
					 fields.colCode = item.code;
					 modelField.push(fields);
				 })
			 }else{
				 for (var key in colData){
					 fields = {}
					 fields.colCode = key;
					 modelField.push(fields);
				 }
			 }
			 $('#groupName').val('');
			$('#groupName').attr("readOnly",false)
			 /* for (var key in colData){
				 fields = {}
				 fields.colCode = key;
				 modelField.push(fields);
			 } */
			 
			 
			 
			 $('#myModalLabel').html("<@spring.message 'field.addGroupField'/>");
			 modelTable.bootstrapTable('refreshOptions',{
				 data: modelField,
				 pagination: true,
                 sidePagination: 'client',
                 pageList: [50]
			 });
		 });
		 
		 $('#groupSureBtn').click(function(){
			 $('#groupEditForm').data('bootstrapValidator').validate();
			 if ($('#groupName').val() == '' || $('#groupCode').val() == ''){
				 return false;
			 }
			 var selections = modelTable.bootstrapTable('getSelections');
			 var modelAllData = modelTable.bootstrapTable('getData');
			 var codeStr = '';
			 var sureIndex = groupIndex;
			 if (doType == 'edit'){
				 sureIndex = checkedIndex;
			 }
			 $.each(selections, function(i,selMap){
				codeStr = codeStr + "," + selMap.colCode;
			 })
			 
			 var groupRow = {}
			 groupRow.dataCols = codeStr.substring(1);
			 groupRow.groupField = $('#groupCode').val();
			 groupRow.groupName = $('#groupName').val();
			 groupRow.doType = doType;
			 groupRow.colJson = modelAllData;
			 groupRow.id = sureIndex;
			 groupRow.reportId = reportId;
			 groupData.push(groupRow)
			  $.ajax({
	    	        url:'${request.contextPath}/report/configure/colConf/submitGroup',
	    	        type:'post',
	    	        contentType: 'application/json',
	    	        data:JSON.stringify(groupRow),
	    	        dataType:'json',
	    	        success:function(data){
	    	        	if (doType == 'add'){
	    					 groupIndex ++;
	    					 
	    				 }else if(doType == 'edit'){
	    					 mtable.bootstrapTable('updateRow', {
	    						 index: checkedIndex, 
	    						 row: groupRow
	    					 });
	    				 }
	    	        	mtable.bootstrapTable('refresh') ;
	    	        }
	    		});			  
		 });
		 $('#editGroup').click(function(){
			 doType = 'edit'
			 var editSel = mtable.bootstrapTable('getSelections');
			 if(editSel.length == 0){
				 bootbox.alert("<@spring.message 'msg.chooseDataWillBeEdited' />", function () {
	    				return;
			      })
			 }else if(editSel.length > 1){
				 bootbox.alert("<@spring.message 'msg.onlyChooseOneRecord' />", function () {
	    				return;
			      })
			 }else{
				 
				$('#groupName').attr("readOnly",true)
				 var modelField = [];
				 var selectedCols = editSel[0].dataCols;
				 var selArray = selectedCols.split(",");
				 if(colData.length > 1){
					 var obj = colData[0];
					 for (var key in obj){
						 var colObj = obj[key];
						 fields = {};
						 fields.colCode = colObj.code;
						 for(var str in selArray){
							 var sstr = selArray[str];
							 if(key == sstr){
								 fields.check = true;
							 }
						 }
						 modelField.push(fields);
					 }
				 }else{
					 for (var key in colData){
						 fields = {}
						 fields.colCode = key;
						 for(var str in selArray){
							 var sstr = selArray[str];
							 if(key == sstr){
								 fields.check = true;
							 }
						 }
						 modelField.push(fields);
					 }
				 }
/* 				 var editJson =  editSel[0].colJson;
 */				 checkedIndex = editSel[0].id;
				 $('#groupName').val(editSel[0].groupField);
				 $('#myModalLabel').html("<@spring.message 'field.editGroupField'/>");
				 modelTable.bootstrapTable('refreshOptions',{
					 data: modelField,
					 pagination: true,
	                 sidePagination: 'client',
	                 pageList: [50]
				 })
				 $("#groupFieldModal").modal('show');
			 }
		 });
		 
		 $('#removeGroup').click(function(){
			 	var groupFields = $.map(mtable.bootstrapTable('getSelections'), function (row) {
	                return row.groupField;
	            });
			 	 $.ajax({
		    	        url:'${request.contextPath}/report/configure/colConf/removeGroup/'+reportId,
		    	        type:'post',
		    	        contentType: 'application/json',
		    	        data:JSON.stringify(groupFields),
		    	        dataType:'json',
		    	        success:function(data){
		    	        	mtable.bootstrapTable('refresh');
		    	        }
		    		});
		 });

			$("#lastStep").click(function(){
				window.history.back(-1);
			});
			
			$("#nameAlert .close").click(function(){
				$("#nameAlert").hide();
			});
		 
	});

</script>
</@layout.defaultLayout>